import React, {useEffect, useReducer, useRef, useState} from 'react';
import './index.less'
import LeftMenu from "@/components/LeftMenu";
import moment from 'dayjs'
import NumWheel from "@/components/NumWheel"
import '../map.less'
import {useRequest} from "ahooks";
import {
    getSaturationByZoneCode,
    getSaturationCount,
    getScenicAreaTrend,
    getScenicCurrentPassenger,
    getScenicKlRealMonitorList,
    getScenicPassengerPageList
} from "@/services/scenic.ts";
import {getCurrentUser} from "@/utils/authority.ts";
import ZebraCrossingTable from "@/components/ZebraCrossingTable";
import PageQuery from "@/pages/map/scenic/components/PageQuery";
import {Card, Pagination} from "antd";
import {merge} from "@ant-design/pro-components";
import {message, notification} from "@/theme/EscapeAntd.tsx";
import {ReloadOutlined} from "@ant-design/icons"
import * as ReactDOMServer from 'react-dom/server';
import useBaseFontSize from "@/hooks/useBaseFontSize.ts";
import AppConfig from "@/config";
import {fade, getZoneLevel, url} from "@/utils/util.ts";
import {useToken} from "antd/es/theme/internal";
import ArchivesModal from "@/components/ArchivesModal";
import {ScenicLevelEnum} from "@/enums/scenic/enum.ts";
import Line from '@/components/charts/Line/new';
import MapBox from '@/pages/map-box';

const pageItemColor: any = {
    '报警': '#E02020',
    '拥挤': '#FF9400',
    '适中': '#ffcd42',
    '舒适': '#6dd400',
};

const saturationCountMap = {
    '报警': {
        name: '报警',
        className: 'type-red',
        icon: url('tourist/warning.png'),
        count: 0,
    },
    '拥挤': {
        name: '拥挤',
        className: 'type-orange',
        icon: url('tourist/traffic.png'),
        count: 0,
    },
    '适中': {
        name: '适中',
        className: 'type-yellow',
        icon: url('tourist/normal.png'),
        count: 0,
    },
    '舒适': {
        name: '舒适',
        className: 'type-green',
        icon: url('tourist/crowded.png'),
        count: 0,
    }
}


const Index: React.FC = () => {
    const {components: {scenic: {marker:any}}, ...mapConfig} = AppConfig.map;
    const token = useToken();

    const mapRef = useRef<any>()
    const distRef = useRef<any>()
    const scenicListRef = useRef<any>()
    const markerRenderTimerRef = useRef<any>();
    const [mapLoading, setMapLoading] = useState<boolean>(true);

    const zoneCode = getCurrentUser().zoneCode;
    const baseFontSize = useBaseFontSize();

    const [time, setTime] = useState<string>(moment().format('YYYY-MM-DD HH:mm:ss'))

    //右侧列表查询条件
    const [pageParams, setPageParams] = useState<any>({
        zoneCode: zoneCode,
        type: 'CURRENT',
        size: 10,
        current: 1,
    });

    //map初始化完成后回调
    const mapOnLoad = (map: any) => {
        mapRef.current = map;
        setMapLoading(false);
        startMarkerInterval();
       
    }

    //点击reload按钮触发
    const mapReload = () => {
        distRef.current && distRef.current.destory();
        mapRef.current.clearMap();
       
        startMarkerInterval();
    }

  
    //结束地图景区marker定时切换
    const endMarkerInterval = () => {
        if (markerRenderTimerRef.current) {
            clearInterval(markerRenderTimerRef.current);
            markerRenderTimerRef.current = null;
        }
    }

    //开始地图定时遍历弹出景区标点
    const startMarkerInterval = () => {
        endMarkerInterval();
        const renderMarker = () => {
            mapRef.current.clearMap();
            const list = getMarkerDataRandom();
            if (list && list.length) {
                drawMarker(list);
            } else {
                setTimeout(renderMarker, 100)
            }
        };
        renderMarker();
        markerRenderTimerRef.current = setInterval(renderMarker, 5000);
    };

    const [modalState, dispatchModal] = useReducer((_: any, action: any) => {
        return {...action};
    }, {visible: false})

    //地图画点
    const drawMarker = (list: any[]) => {
        list.forEach(item => {
            const infoWindowMarket = new AMap.Marker({
                position: item.lnglat,
                content: ReactDOMServer.renderToString(
                    marker.render(item)
                ),
                offset: new AMap.Pixel(
                    -130 * baseFontSize,
                    (marker.offsetHeight) * baseFontSize
                ) //设置偏移量
            });
            //marker点击事件
            infoWindowMarket.on('click', () => {
                endMarkerInterval();
                dispatchModal({
                    visible: true,
                    payload: {...item, type: "SCENIC"}
                })
            })

            mapRef.current.add([
                    new AMap.Marker({
                        position: item.lnglat,
                        content: "<div class='map-point'></div>",
                        anchor: 'center', //设置锚点
                        zIndex: 9999,
                        offset: new AMap.Pixel(0, 0) //设置偏移量
                    }),
                    infoWindowMarket
                ]
            )
        })
    };

    //随机抽取n个景区
    const getMarkerDataRandom = (n = 1) => {
        const list: any = {};
        if (scenicListRef.current?.list?.length) {
            //循环20次，防止无效数据过多
            for (let i = 0; Object.values(list).length < n && i < 20; i++) {
                const randomIndex = Math.floor(Math.random() * (scenicListRef.current.list.length - 1));
                const item = scenicListRef.current.list[randomIndex];
                if (!list[item.code] && item.longitude && item.latitude) {
                    list[item.code] = {
                        lnglat: [item.longitude, item.latitude],
                        current: item.currentTourist,
                        DAY: item.totalTourist,
                        id: item.id,
                        name: item.fullName,
                        levelName: ScenicLevelEnum[item.level || 0]
                    };
                }
            }
        }
        return Object.values(list);
    }

    //显示景区地图marker
    const showScenicOnMap = (item: any) => {
        if (!(item.longitude && item.latitude)) {
            notification.error({
                key: 'request',
                description: '经纬度不存在，不能进行定位',
                message: '提示',
            });
            return false;
        }
        // if (!mapRef.current) {
        //     message.warning("请等待地图渲染完成");
        //     return;
        // }
        // mapRef.current.panTo([item.longitude, item.latitude]);
        // endMarkerInterval();
        // mapRef.current.clearMap();
        // drawMarker([{
        //     lnglat: [item.longitude, item.latitude],
        //     current: item.currentTourist,
        //     DAY: item.totalTourist,
        //     id: item.id,
        //     name: item.fullName,
        //     levelName: ScenicLevelEnum[item.level || 0]
        // }])
    }


    //当前重点景区客流量
    const {
        data: currentPassenger,
        run: getCurrentPassenger
    } = useRequest(() => getScenicCurrentPassenger({zoneCode, type: 'CURRENT'}))

    //当前景区平均饱和度
    const {
        data: saturation,
        run: getSaturation
    }: any = useRequest(() => getSaturationByZoneCode({zoneCode, type: 'CURRENT'}))

    //实时客流趋势
    const {data: trendData, run: getTrendData,loading:TrendLoad} = useRequest(() => {
        return getScenicAreaTrend({
            scope: 'day',
            zoneCode,
            dateStr: moment().format('YYYY-MM-DD'),
            type: 'CURRENT',
        }).then((res: any) => {
            const keys: any[] = [], momSeriesData: any[] = [];
            res.forEach((item: any) => {
                const hour = Number(item.key.split(':')[0]);
                if (hour >= 7 && hour <= Math.min(new Date().getHours(), 19)) {
                    keys.push(item.key);
                    momSeriesData.push(item.value ? item.value : '-')
                }
            })

            return {
                option:{
                    color: ['#2cb9ff', '#fff'],
                    legend: {
                      data: ['当日累计客流'],
                      left: 'right',
                      itemWidth: 20,
                      itemHeight: 3,
                      itemGap: 40,
                    },
                    grid: {
                      top: 30,
                      bottom:10
                    },
                    xAxis: {
                      type: 'category',
                      data: keys || [],
                    },
                    yAxis: {
                      // name: '万元',
                      type: 'value',
                      axisLine: {
                        show: false,
                      },
                      splitLine: {
                        show: true,
                        lineStyle: {
                          width: 1,
                          color: 'rgba(255, 255, 255, 0.1)',
                        },
                      },
                    },
                  },
                  series:[
                    {
                      name: '当日累计客流',
                      type: 'line',
                      showSymbol: false,
                      smooth: true,
                      data: momSeriesData || [],
                      areaStyle: {},
                    },
                  ]
            }
        })
    })

    //子行政区划客流列表
    const {
        data: subAreaList = [],
        loading: subAreaListLoading,
        run: getSubAreaPassengerList
    } = useRequest(() => getScenicKlRealMonitorList({zoneCode}))

    //右侧列表查询
    const {
        data: scenicList,
        run: getPageData,
        loading: scenicListLoading
    }: any = useRequest((params) => {
        const current = params?.page || pageParams.current;
        const query = {...pageParams, current, ...params};
        if (!query.zoneCode) {
            query.zoneCode = zoneCode;
        }
        return getScenicPassengerPageList(query)
    }, {
        onSuccess: (res: any) => {
            console.log('res',res)
            let data:any =[]
            res.list.map((item: any, index: number) => {
                data.push({
                  lng: item.longitude,
                  lat: item.latitude,
                  name: item.fullName,
                  passenger: item.currentTourist,
                  comfortChinese: item.comfortChinese,
                  comment: item.score||"",
                  saturation: item.saturation,
                  isOpen:item.isOpen,
                  resourceId: item.resourceId,
                  id: item.id,
                });
              });
            scenicListRef.current = data

        }
    })

    // 各级别饱和度景区数量查询
    const {
        data: saturationData,
        run: getSaturationData
    }: any = useRequest(() => {
        return getSaturationCount({zoneCode, type: 'CURRENT'}).then((res: any) => {
            const result = JSON.parse(JSON.stringify(saturationCountMap));
            res.forEach((item: any) => {
                result[item.name].count = item.saturation;
            });
            return Object.values(result);
        })
    })

    //右侧列表查询
    const pageParamChange = (params: any) => {
        const {name: scenicName, ...otherParams} = params;
        //数据变化跳转到第一页
        const newParams = {scenicName, ...otherParams, page: 1};
        setPageParams({...pageParams, ...newParams});
        getPageData(newParams)
    }

    const column = [
        {
            title: '区域',
            dataIndex: 'name'
        },
        {
            title: '实时客流',
            dataIndex: 'data',
            render: (obj: any) => `${obj.CURRENT}人`
        },
        {
            title: '客流占比',
            dataIndex: 'data',
            render: (obj: any) => `${obj.percent ? obj.percent * 100 : '-'}%`
        },
    ];

    useEffect(() => {
        setInterval(() => {
            setTime(moment().format('YYYY-MM-DD HH:mm:ss'))
        }, 1000);

        setInterval(() => {
            getCurrentPassenger();
            getSaturation();
            getTrendData();
            getSubAreaPassengerList();
            getSaturationData();
        }, 30000)

        return () => {
            if (markerRenderTimerRef.current) {
                clearInterval(markerRenderTimerRef.current);
                markerRenderTimerRef.current = null;
            }
        }
    }, [])

    const archivesModalClose = () => {
        startMarkerInterval();
        dispatchModal({visible: false})
    }

    return (
        <div className="map-layout scenic-passenger-flow">
            
               {!scenicListLoading&& <MapBox
                    className={'map-box'}
                    list={scenicListRef.current}
                    scenicClick={(item: any) => showScenic(item.id)}
                    mapConfig={{
                    tipMarker: {
                        enable: false,
                    }
                    }}
                />}
                <div className="reload-btn" onClick={mapReload}>
                    <ReloadOutlined/>
                </div>
           
            <div className="left z-10" >
                <LeftMenu group="/scenic" path="/passengerflow"/>
                <div className="number-scroll">
                    <div className="number-scroll-item">
                        <div>{time}</div>
                        <div className="number-scroll-title">重点景区当前客流量</div>
                        <div className="number-scroll-box">
                            <NumWheel value={currentPassenger || 0}/>
                            <span className="number-scroll-unit">人</span>
                            <div className="avg-saturation">
                                平均饱和度 {saturation || 0}
                            </div>
                        </div>
                    </div>
                </div>
                <Card title="重点景区当天客流量趋势" style={{height: '240rem'}}>
                    <div className='h-full'>
                        <Line
                        refreshLoading={TrendLoad}
                            {...trendData}
                        />
                    </div>
                    
                </Card>
                {
                    getZoneLevel(zoneCode) !== 3 &&
                    <Card title="按区域分析" style={{marginTop: '30rem'}}>
                        <ZebraCrossingTable
                            dataSource={subAreaList}
                            loading={subAreaListLoading}
                            columns={column}
                            rowKey={(item: any) => item.code}
                            scrollOut="70rem"
                            style={{
                                height: 'calc(100vh - 900rem)'
                            }}
                        />
                    </Card>
                }

            </div>
            <div className="center">
                <div className="scenic-center-wrapper">
                    <div className={'title'}>重点景区饱和度</div>
                    <div className="scenic-center-group">
                        {saturationData?.map((item: any) => (
                            <div className={`scenic-center-item ${item.className}`} key={item.name}>
                                <div className={'w-[50rem] py-[4rem] pl-[10rem]'}>
                                    <div className="scenic-center-icon"
                                         style={{backgroundImage: `url(${item.icon})`}}></div>
                                    <div className="scenic-center-title">{item.name}</div>
                                </div>
                                <div className="scenic-center-count flex-1">{item.count}</div>
                            </div>
                        ))}
                    </div>
                </div>
            </div>
            <div className="right" style={{paddingBottom: '16rem'}}>
                <Card title="景区实时客流量">
                    <div className="flex-box" style={{height: 'calc(100vh - 400rem)'}}>
                        <PageQuery onChange={pageParamChange}/>
                        <div className="scenic-list flex-box-scalable" style={{overflowY: 'auto'}}>
                            {scenicList?.list?.length > 0
                                && scenicList.list.map((item: any, index: number) => (
                                        <div className="scenic-item" key={index} onClick={() => showScenicOnMap(item)}>
                                            <div className="scenic-item-no">
                                                NO.{(scenicList.current - 1) * scenicList.size + index + 1}
                                            </div>
                                            <div className="scenic-item-content">
                                                <div className="scenic-item-name"> {item.fullName}</div>
                                                <div className="scenic-item-bar">
                                                    <div style={{width: `${item.saturation || '0%'}`}}></div>
                                                </div>
                                            </div>
                                            <div className="scenic-item-count">
                                                <div>
                                                    {item.currentTourist}
                                                    <span className="scenic-item-unit">人</span>
                                                </div>
                                                <div>
                                                    <span className="scenic-item-saturation">
                                                      {item.saturation || '0%'}
                                                    </span>
                                                    <span className="scenic-item-comfort"
                                                          style={{color: item.comfortChinese ? pageItemColor[item.comfortChinese] : ''}}>
                                                            {item.comfortChinese || '-'}
                                                    </span>
                                                </div>
                                            </div>
                                        </div>
                                    ),
                                )}
                        </div>
                        <div className="resource-page-wrappper">
                            <Pagination
                                pageSize={scenicList?.size || 10}
                                current={scenicList?.current || 1}
                                total={scenicList?.total || 0}
                                size="small"
                                showSizeChanger={false}
                                style={{display: 'inline-block'}}
                                onChange={(page) => getPageData({page})}
                            />
                        </div>
                    </div>
                </Card>
            </div>
            {modalState.visible && <ArchivesModal handleClose={archivesModalClose} {...modalState}/>}
        </div>
    );
};

export default Index;